#include "preHeader.h"
#include "VipStorage.h"
#include "Object/Player.h"

VipStorage::VipStorage(Player* pOwner)
: m_pOwner(pOwner)
, m_level(0)
, m_exp(0)
{
}

VipStorage::~VipStorage()
{
}

void VipStorage::OnPay(uint32 payId, time_t payTime)
{
	auto pPayShop = GetDBEntry<PayShop>(payId);
	if (pPayShop == NULL) {
		WLOG("Invalid pay id %u.", payId);
		return;
	}

	for (auto& chequeInfo : pPayShop->buyCheques) {
		m_pOwner->GainCheque(ChequeType(chequeInfo.type),
			chequeInfo.value, CFT_PAY, {payId, (u32)payTime}, true);
	}
	auto itemProps = NewItemProps4FItemInfo(pPayShop->buyItems);
	m_pOwner->GetItemStorage()->CreateAddItemsMail(
		NULL, itemProps.data(), itemProps.size(),
		IFT_PAY, {payId, (u32)payTime}, true);

	m_pOwner->SendOperating4Pay(
		pPayShop->buyPrice, pPayShop->buyGoldValue, pPayShop->itemType);
}

GErrorCode VipStorage::GainExp(uint64 value,
	CHEQUE_FLOW_TYPE flowType, params<uint32> flowParams)
{
	DBGASSERT(value <= INT64_MAX);
	if (value == 0) {
		return CommonSuccess;
	}

	m_exp += value;
	RefreshLevel();

	return CommonSuccess;
}

void VipStorage::BuildCreatePacketForPlayer(INetPacket& pck, Player* pPlayer)
{
	pck << m_level << m_exp;
}

void VipStorage::RefreshLevel()
{
	m_level = uint32(m_exp / 100);
	m_pOwner->SendOperating4PlayActvt(
		OperatingPlayType::VipLevelReach, {GetLevel()});
}

std::string VipStorage::Save() const
{
	TextPacker packer;
	packer << m_exp;
	return packer.str();
}

void VipStorage::Load(const std::string& data)
{
	TextUnpacker unpacker(data.c_str());
	unpacker >> m_exp;
}
